<template>
  <div class="def-pagination" :style="{ justifyContent: getAlign }">
    <el-pagination
      v-model:currentPage="currentPageVal"
      v-model:page-size="pageSizeVal"
      :total="totalVal"
      :page-sizes="pageSizesVal"
      layout="total, sizes, prev, pager, next, jumper"
      background
      :disabled="isLoading"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
</template>

<script lang="ts" setup>
import { ref, PropType, computed, watch, inject } from 'vue'
import { TPaginationAlign } from './types'

/* 参数声明 */
const props = defineProps({
  // 当前页码 v-model
  currentPage: {
    type: Number,
    required: true
  },
  // 每页条数 v-model
  pageSize: {
    type: Number,
    required: true
  },
  // 总条数
  total: {
    type: Number,
    default: 0
  },
  // 分页组件对齐方式
  align: {
    type: String as PropType<TPaginationAlign>,
    default: 'center'
  }
})
const emits = defineEmits(['update:currentPage', 'update:pageSize'])
const isLoading = inject('isLoading')

const currentPageVal = ref(props.currentPage)
const pageSizeVal = ref(props.pageSize)
const totalVal = ref(props.total)
const pageSizesVal = ref([
  props.pageSize * 1,
  props.pageSize * 2,
  props.pageSize * 3,
  props.pageSize * 4,
  props.pageSize * 5
])

watch(
  () => props.total,
  (value) => {
    totalVal.value = value
  }
)

// 分页对齐方式计算
const getAlign = computed(() => {
  let align = ''
  if (props.align === 'left') {
    align = 'flex-start'
  } else if (props.align === 'center') {
    align = 'center'
  } else if (props.align === 'right') {
    align = 'flex-end'
  }
  return align
})

// 注入获取表格列表方法
const getList: any = inject('getList')
// 页码改变
const handleCurrentChange = (currentPage: number) => {
  currentPageVal.value = currentPage
  emits('update:currentPage', currentPage)
  getList?.()
}
// 每页条数改变
const handleSizeChange = (pageSize: number) => {
  pageSizeVal.value = pageSize
  // 非第一页时 每页条数改变重置页码为第一页
  initCurrentPage()
  emits('update:pageSize', pageSize)
  getList?.()
}

const initCurrentPage = () => {
  if (currentPageVal.value !== 1) {
    currentPageVal.value = 1
    emits('update:currentPage', 1)
  }
}

defineExpose({
  initCurrentPage
})
</script>

<style scoped lang="scss">
.def-pagination {
  @include flexRow;
  padding: 30px 0 0;
}
</style>
